package org.wzl.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: 卫志龙
 * @date: 2024年06月27日 20:35
 */
@Slf4j
@Component
public class RequestTimeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put("requestTime", System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long requestTime = exchange.getAttribute("requestTime");
            if (requestTime != null) {
                log.info("request Url{},{}ms", exchange.getRequest().getURI().getRawPath(), (System.currentTimeMillis() - requestTime));
            }
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
